const express = require("express");
const Users = require("../models/Reg");
const db = require("../db/index");
const jwt = require("jsonwebtoken")
const cookieParser = require("cookie-parser")
const router = new express.Router();
router.use("/", async (req, res, next) => {
    await db;
    next();
})
router.use(cookieParser())
const secret = "abc";
router.post("/login", async (req, res) => {
    const user = req.body;
    const result = await Users.findOne({
        username: user.username
    }, {
        _id: 0,
        __v: 0
    })
    if (result) {
        if (user.username == result.username && user.password == result.password) {
            jwt.sign(user,secret,{
                expiresIn:"1h"
            },(err,token)=>{
                if(!err){
                    res.cookie("token",token,{
                        maxAge:1000*60*60
                    })
                    res.send("登录成功")
                }else{
                    console.log(err);
                    res.send("用户名或密码错误")
                }
            })
        }else{
            res.send("用户名或密码错误")

        }
    }else{
        res.send("用户名或密码错误")
    }
})
module.exports = router;